<?php

class HubsController extends Zend_Controller_Action {

    protected $_log;
    protected $doctrineContainer;

    public function init() {
        $this->_log = Zend_Registry::get('log');
        $this->doctrineContainer = Zend_Registry::get('doctrine');
    }

    public function indexAction() {
        $this->view->headTitle($this->view->translate->_('Hubs'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();  
        $hubs = $em->getRepository('Jhub1db\Entity\Jhub1service')->getAllOrdered();       
        $this->view->hubs = $hubs;
    }
    
    public function newAction() { 
        
    }  
#ADD HUB PROCESS
    public function addusbhubAction() {
        $addSession = new Zend_Session_Namespace('addHub');
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        $usbhubid = $this->_getParam('usbhubid');
        #validate hub id here using web services
        # if not validated $this->_redirect("hubs/add");
        
        $addSession->hubType = "USB";
        $addSession->usbHubId = $usbhubid;
        $this->_redirect("hubs/addagent"); 
    }    
    
    
    public function addAction() {
        $addSession = new Zend_Session_Namespace('addHub');
        $this->view->headTitle($this->view->translate->_('Add new hub'), 'PREPEND');
        if ($this->isNewUsbHubAvailable()) {
            $this->view->isUSB = 1;
        }
        if (preg_match("/^(USB|ETH|VIR)/", $this->_getParam('hubType'))) {
            if($this->_getParam('hubType') != $addSession->hubType) {
                $addSession->agentType = 0;
                $addSession->basicConfig = 0;
                $addSession->usbHubId = "";
                $addSession->serviceConfig = "";
                $addSession->serviceMainConfig = "";
                $addSession->serviceConfig = "";
                $addSession->serviceRawConfig = "";               
            }
            $addSession->hubType = $this->_getParam('hubType');
            
            $this->_redirect("hubs/addagent");            
        }
        $this->view->hubType = $addSession->hubType;
    }

    public function addagentAction() {
        $addSession = new Zend_Session_Namespace('addHub');
        $this->view->headTitle($this->view->translate->_('Add new hub - select agent'), 'PREPEND');

        if ($this->_getParam('agentType') > 0) {
            if($this->_getParam('agentType') != $addSession->agentType) {
                $addSession->basicConfig = 0;
                $addSession->serviceMainConfig = "";
                $addSession->serviceConfig = "";
                $addSession->serviceRawConfig = "";
            }            
            $addSession->agentType = $this->_getParam('agentType');
            if ($this->_getParam('selectedUsbHubId')) {
                $addSession->usbHubId = $this->_getParam('selectedUsbHubId');
            }
            $this->_redirect("hubs/addconfig");            
        }
        
        $this->view->agentType = $addSession->agentType;
        $this->view->hubType   = $addSession->hubType;
        $this->view->usbHubId  = $addSession->usbHubId;
        if ($this->view->hubType == "USB") {
            $gw = new Application_Model_SystemGateway();
            $this->view->newHubs = json_decode($gw->getNewUSBHubs(), true);
        }
        if (preg_match("/^(USB|ETH|VIR)/", $addSession->hubType)) {
            
        } else {
            $this->_redirect("hubs/add");
        }
        $em = $this->doctrineContainer->getEntityManager();
        $agents = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findBy(array('iftype' => $addSession->hubType));
        $this->view->agents = array();
        foreach ($agents as $agent) {
            if ($agent->getAgent()->getVisible() == 1) {
                $id = $agent->getId();
                $this->view->agents[$id] = $agent->getAgent()->getAname() . " - " . $agent->getDevTypeName() . "  " . $agent->getAgent()->getDescription() . " Provided by: " . $agent->getAgent()->getDeveloper();
            }
        }
    }

    public function addconfigAction() {
        $addSession = new Zend_Session_Namespace('addHub');
        $this->view->headTitle($this->view->translate->_('Add new hub - config'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();
        if (preg_match("/^(USB|ETH|VIR)/", $addSession->hubType) && $addSession->agentType > 0) {
            $agents = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findBy(array('iftype' => $addSession->hubType, 'id' => $addSession->agentType));
            $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/DefaultAgentConfigForm.ini", 'development');
            
            $form = new Jhub1_Form($config->user->agent);
            if ($this->_request->isPost()) {
                $formData = $this->_request->getPost();
                if ($form->isValid($formData)) {
                    $addSession->serviceMainConfig = $formData;
                    $addSession->basicConfig = 1;
                    $this->_redirect("hubs/addservice");   
                } else {
                    $form->populate($formData);
                }
            }
            if(is_array($addSession->serviceMainConfig)){
                $form->populate($addSession->serviceMainConfig);
            }
            $this->view->form = $form;
            
        } else {
            if (preg_match("/^(USB|ETH|VIR)/", $addSession->hubType)) {
                
            } else {
                $this->_redirect("hubs/add");                
            }
            if ($addSession->agentType > 0) {
                
            } else {
                $this->_redirect("hubs/addagent");                
            }            
        }
    }    

    public function addserviceAction() {
        $addSession = new Zend_Session_Namespace('addHub');
        $this->view->headTitle($this->view->translate->_('Add new hub - service config'), 'PREPEND');

        $em = $this->doctrineContainer->getEntityManager();
        if (preg_match("/^(USB|ETH|VIR)/", $addSession->hubType) && $addSession->agentType > 0  && $addSession->basicConfig == 1) {
                $agents = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findBy(array('iftype' => $addSession->hubType, 'id' => $addSession->agentType));
                if (count($agents) == 1) {
                if ($agents[0]->getConfigTemplate() != "" && $this->fileExists($agents[0]->getConfigTemplate())) {
                    $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/" . $agents[0]->getConfigTemplate(), 'form');
                    $form = new Jhub1_Form($config->hub->custom);

                    if ($this->_request->isPost()) {
                        $formData = $this->_request->getPost();
                        if ($form->isValid($formData)) {
                            unset($formData['submit']);
                            $dbSave = json_encode($formData);
                            $addSession->serviceConfig = $dbSave;
                            $addSession->serviceRawConfig = $formData;
                            $this->_redirect("hubs/addsave");   
                        } else {
                            $form->populate($formData);
                        }
                    }
                    if(is_array($addSession->serviceRawConfig)){
                        $form->populate($addSession->serviceRawConfig);
                    }
                    $this->view->form = $form;
                    
                } else {
                    $this->_redirect("hubs/addsave");
                }
            } else {
                echo $this->view->errorMessage = 1;
                }
        } else {
            if (preg_match("/^(USB|ETH|VIR)/", $addSession->hubType)) {
                
            } else {
                $this->_redirect("hubs/add");                
            }
            if ($addSession->agentType > 0) {
                
            } else {
                $this->_redirect("hubs/addagent");                
            }
            if ($addSession->basicConfig == 1) {
                
            } else {
                $this->_redirect("hubs/addconfig");                
            }            
        }        
        
    }    

    public function addsaveAction() {
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();
        $addSession = new Zend_Session_Namespace('addHub');
        $em = $this->doctrineContainer->getEntityManager();
  
        $agents = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findBy(array('iftype' => $addSession->hubType, 'id' => $addSession->agentType));
        
        $service = new Jhub1db\Entity\Jhub1service($addSession->serviceMainConfig["name"]);
        $service->setOrderi($addSession->serviceMainConfig["orderi"]);
        $service->setActive($addSession->serviceMainConfig["active"]); 
        $service->setAccesstype($addSession->serviceMainConfig["accesstype"]);
        $service->setConfig($addSession->serviceConfig);
        if ($addSession->usbHubId) {
            $service->setDev($addSession->usbHubId);
            $gw = new Application_Model_SystemGateway();
            $gw->markHubInstalled($addSession->usbHubId);
        }
        $service->setAgentdev($agents[0]);
        $em->persist($service);    
        $em->flush();

        if ($agents[0]->getFixedDevices() != "" && $this->fileExists($agents[0]->getFixedDevices())) {

           $defDevices = new Zend_Config_Json(APPLICATION_PATH . '/configs/' . $agents[0]->getFixedDevices()); 
        #   $defDevices->toArray();
      #      var_dump($defDevices->toArray());
      ##     die;
           $this->createDefaultDevices($service, $defDevices->toArray()); 
        }        
        $addSession->unsetAll();
        $this->_redirect("hubs/index");
    }
#END OF ADD HUB PROCESS
    
    public function actionsAction() {
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();

        $action = $this->_getParam('doaction');
        $hubids = $this->_getParam('hubid');
        $hubsItems = count($hubids);
        if (preg_match("/^(public|private|active|inactive|delete)/", $action) && $hubsItems > 0) {
            $em = $this->doctrineContainer->getEntityManager();            
            if ($action == "public") {
                foreach($hubids as $hubid) {
                     $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
                     $hub[0]->setAccesstype(1);
                     $em->persist($hub[0]);
                }
            } else if ($action == "private") {
                foreach($hubids as $hubid) {
                     $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
                     $hub[0]->setAccesstype(0);
                     $em->persist($hub[0]);    
                }                
            } else if ($action == "active") {
                foreach($hubids as $hubid) {
                     $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
                     $hub[0]->setActive(1);
                     $em->persist($hub[0]);    ;
                }   
            } else if ($action == "inactive") {
                foreach($hubids as $hubid) {
                     $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
                     $hub[0]->setActive(0);
                     $em->persist($hub[0]);    
                }                   
            } else if ($action == "delete") {
                foreach($hubids as $hubid) {
                     $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hubid));
                     $em->remove($hub[0]);    
                }               
            } else {
                $this->_redirect("hubs/index");                
            }
            $em->flush();
        } else {
           $this->_redirect("hubs/index"); 
        }
        $this->_redirect("hubs/index");
    }

    public function detailsAction() {
        $hid = $this->_getParam('hid');        
        $this->view->headTitle($this->view->translate->_('Edit hub details'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();
        if ($hid > 0) {
            $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hid));
            
            if($hub[0] instanceof Jhub1db\Entity\Jhub1service) {
               $hubForm = $this->convertHubDetailsToForm($hub[0]);
            } else {
               $this->_redirect("hubs/index");                 
            }
            
            $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/DefaultAgentConfigForm.ini", 'development');
            $form = new Jhub1_Form($config->user->agent);
     
            if ($this->_request->isPost()) {
                $formData = $this->_request->getPost();
                if ($form->isValid($formData)) {
                    
                    #save here
                    
                    $this->_redirect("hubs/details");   
                }
            }

            $form->populate($hubForm);
            $this->view->form = $form;
            
        } else {
            $this->_redirect("hubs/index");                       
        }
        
        
        
     /*
        if ($aid > 0) {
            $this->view->headTitle($this->view->translate->_('Agent details'), 'PREPEND');
            $em = $this->doctrineContainer->getEntityManager();
            $agentsHubs = $em->getRepository('Jhub1db\Entity\Jhub1agentdev')->findAll();
            $this->view->agentsHubs = array();
            foreach ($agentsHubs as $dev) {
               if($dev->getAgent()->getId() == $aid) {
                   $this->view->agentsHubs[] = $dev;
               }
            }
            #$this->view->agentsHubs = $agentsHubs;
            /**
             * @todo: implement all the Agents database model and pick Agent details in here
             */
        /*
        } else {
            $this->_redirect("agents/index");
        }
        */
    }    

    public function editAction() {
        $this->_helper->layout()->disableLayout();
#        $this->getHelper('viewRenderer')->setNoRender();
        $hid = $this->_getParam('hid');
        $this->view->headTitle($this->view->translate->_('Edit hub config'), 'PREPEND');
        $em = $this->doctrineContainer->getEntityManager();
        if ($hid > 0) {
            $hub = $em->getRepository('Jhub1db\Entity\Jhub1service')->findBy(array('id' => $hid));
            
            if($hub[0] instanceof Jhub1db\Entity\Jhub1service) {
               $agentDev = $hub[0]->getAgentdev();
               $agentDevConfigTmpl = $agentDev->getConfigTemplate();
               $hubForm = json_decode($hub[0]->getConfig(), true);
            } else {
               $this->_redirect("hubs/index");                 
            }
            
            $config = new Zend_Config_Ini(APPLICATION_PATH . "/forms/" . $agentDevConfigTmpl, 'form');
            $form = new Jhub1_Form($config->hub->custom);
     
            if ($this->_request->isPost()) {
                $formData = $this->_request->getPost();
                if ($form->isValid($formData)) {
                    
                    #save here
                    
                    $this->_redirect("hubs/details");   
                }
            }

            $form->populate($hubForm);
            $this->view->form = $form;
            
        } else {
            $this->_redirect("hubs/index");                       
        }
    }     
    
    private function fileExists($file) {
        return 1;
    }

    private function createDefaultDevices($service, $defDevicesArr) {
        $em = $this->doctrineContainer->getEntityManager();        
        foreach ($defDevicesArr as $newDevice) {
            
           $attributes = new Jhub1db\Entity\Jhub1attributes($newDevice);
           $em->persist($attributes);         
            /**
             * @todo: convert this part to array parameters rather - make it more error proof
             */
           $device = new Jhub1db\Entity\Jhub1device($service);
           $device->setAttributes($attributes);
           $device->setDevicetype($newDevice['type']);
           $device->setRemovable($newDevice['removable']);
           $device->setOrder($newDevice['orderi']);
           $device->setAddress($newDevice['address']);
           $device->setFixedstatic($newDevice['fixedstatic']);
           $device->setUpdated(time());
           $em->persist($device);
           
           $em->flush();      
        }
        return;
    }
    
    private function convertHubDetailsToForm($hubs) {
        $retVal = array();
        $retVal['name'] = $hubs->getName();
        $retVal['orderi'] = $hubs->getOrderi();
        $retVal['accesstype'] = $hubs->getAccesstype();
        $retVal['active'] = $hubs->getActive();
        return $retVal;
    }
    
    private function isNewUsbHubAvailable() {
        $gw = new Application_Model_SystemGateway();
        $response = json_decode($gw->getNewUSBHubs(),true);
        if (count($response) > 0) {
               return 1;
        }
        return 0;
    }
}

